package com.stylefeng.guns.modular.apple_sign_task_manage.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.modular.apple.utils.TimeUtil;
import com.stylefeng.guns.modular.apple.vo.Paging;
import com.stylefeng.guns.modular.apple_id_manage.model.AppleIds;
import com.stylefeng.guns.modular.apple_id_manage.service.IAppleIdsService;
import com.stylefeng.guns.modular.apple_sign_task_manage.bo.DeviceTotalBO;
import com.stylefeng.guns.modular.apple_sign_task_manage.bo.MerchantBO;
import com.stylefeng.guns.modular.apple_sign_task_manage.bo.MerchantInfoBO;
import com.stylefeng.guns.modular.apple_sign_task_manage.bo.SignTaskBO;
import com.stylefeng.guns.modular.apple_sign_task_manage.model.*;
import com.stylefeng.guns.modular.apple_sign_task_manage.dao.SignTasksMapper;
import com.stylefeng.guns.modular.apple_sign_task_manage.service.ISignTasksService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.user_buy_device.dao.UserBuyDeviceInfoMapper;
import com.stylefeng.guns.modular.user_buy_device.model.UserBuyDeviceDO;
import com.stylefeng.guns.modular.user_buy_device.model.UserBuyDeviceInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * 签包任务表 服务实现类
 * </p>
 *
 * @author godrui
 * @since 2020-06-20
 */
@Service
public class SignTasksServiceImpl extends ServiceImpl<SignTasksMapper, SignTasks> implements ISignTasksService {

    @Resource
    private UserBuyDeviceInfoMapper buyDeviceInfoMapper;

    @Resource
    private IAppleIdsService idsService;

    /**
     * 获取签包应用列表
     * @param page
     * @param limit
     * @return
     */
    @Override
    public Object listSignTask(String sortValue,Integer merchantName,Integer page,Integer limit, Integer status, String signBeginTime, String signEndTime) {
        int start = (page > 0?page-1:0) * limit;
        Integer userId;
        if (isAdmin()){
            userId = merchantName == 0?null:merchantName;
        }else{
            userId = ShiroKit.getUser().getId();
        }
        Integer totalCount = this.baseMapper.findSignCount(userId,status,signBeginTime,signEndTime);

        List<SignTaskBO> signTaskBOList = this.baseMapper.listSignTask(sortValue,userId,start,limit,status,signBeginTime,signEndTime);
        Paging<SignTaskBO> paging = new Paging<>();
        paging.setTotal(totalCount.longValue());
        paging.setItems(signTaskBOList);

        return paging;
    }

    /**
     * 应用设备信息
     * @return
     */
    @Override
    public Object deviceInfoOfApp(String beginTime,String endTime) {

        Integer useId = isAdmin()?null:ShiroKit.getUser().getId();

        DeviceTotalCountDO deviceCount = this.baseMapper.findDeviceTotalCount(useId,beginTime, endTime);
        Integer appCount = this.baseMapper.findAllAppCount(useId,beginTime, endTime);
        Integer buyDeviceCount = 0;
        if (isAdmin()){
            buyDeviceCount = idsService.selectCount(null) * 100;
        }else{
            UserBuyDeviceInfo deviceInfo = new UserBuyDeviceInfo();
            deviceInfo.setUserId(ShiroKit.getUser().getId());
            UserBuyDeviceInfo _deviceInfo = buyDeviceInfoMapper.selectOne(deviceInfo);
            if (_deviceInfo != null){
                buyDeviceCount = _deviceInfo.getDeviceCount();
            }
        }
        Integer remainingCount = 0;
        if (isAdmin()){
            remainingCount = idsService.getEnableUseCount();
        }else{
            remainingCount = buyDeviceCount - deviceCount.getTotalCount();
        }

        return DeviceTotalBO.builder()
                .deviceCount(deviceCount.getTotalCount())
                .appCount(appCount)
                .buyDeviceCount(buyDeviceCount)
                .remainingCount(remainingCount)
                .build();
    }

    /**
     * 获取每日签包设备信息
     * @param beginTime
     * @param endTime
     * @return
     */
    @Override
    public Object getEveryDayDeviceInfo(String merchantId,String beginTime, String endTime) {
        if (StringUtils.isEmpty(beginTime) && StringUtils.isEmpty(endTime)){
            Date dt = new Date();
            endTime =  TimeUtil.dateToGTMString(dt,"yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR,-30);//日期减30天
            Date bdt = calendar.getTime();
            beginTime = TimeUtil.dateToGTMString(bdt,"yyyy-MM-dd");
        }else if(StringUtils.isEmpty(beginTime) && !StringUtils.isEmpty(endTime)){
            try {
                Date dt = TimeUtil.getGMTDateFormat("yyyy-MM-dd").parse(endTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(dt);
                calendar.add(Calendar.DAY_OF_YEAR,-30);//日期减30天
                Date bdt = calendar.getTime();
                beginTime = TimeUtil.dateToGTMString(bdt,"yyyy-MM-dd");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else if(!StringUtils.isEmpty(beginTime) && StringUtils.isEmpty(endTime)){
            try {
                Date dt = TimeUtil.getGMTDateFormat("yyyy-MM-dd").parse(beginTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(dt);
                calendar.add(Calendar.DAY_OF_YEAR,30);//日期加30天
                Date bdt = calendar.getTime();
                if (bdt.getTime() < new Date().getTime()){
                    endTime = TimeUtil.dateToGTMString(bdt,"yyyy-MM-dd");
                }else {
                    endTime = TimeUtil.dateToGTMString(new Date(),"yyyy-MM-dd");
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else{
            try {
                Date dt = TimeUtil.getGMTDateFormat("yyyy-MM-dd").parse(beginTime);
                Date edt = TimeUtil.getGMTDateFormat("yyyy-MM-dd").parse(endTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(dt);
                calendar.add(Calendar.DAY_OF_YEAR,30);//日期加30天
                Date bdt = calendar.getTime();
                if (bdt.getTime() < edt.getTime()){
                    //结束日期离开始日期大于30天
                    throw new GunsException(BizExceptionEnum.SIGN_DEVICE_DATE_MT_30_DAYS);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        Integer useId;
        if (StringUtils.isEmpty(merchantId) || "0".equals(merchantId)){
            useId = isAdmin()?null:ShiroKit.getUser().getId();
        }else{
            useId = Integer.parseInt(merchantId);
        }

        List<DeviceInfoOfAppDO> everyDayDeviceCount =
                this.baseMapper.findEveryDaySignCount(useId,beginTime, endTime);
        int size = everyDayDeviceCount.size();
        String[] signTimeArr = new String[size];
        Integer[] deviceCountArr = new Integer[size];
        AtomicInteger index = new AtomicInteger();
        everyDayDeviceCount.forEach(c->{
            signTimeArr[index.get()] = TimeUtil.dateToGTMString(c.getSignTime(),"yyyy-MM-dd");
            deviceCountArr[index.get()] = c.getDeviceCount();
            index.getAndIncrement();
        });

        return DeviceTotalBO.builder()
                .signTimeArr(signTimeArr)
                .deviceCountArr(deviceCountArr)
                .build();
    }

    @Override
    public Object getMerchantDeviceInfo(String merchantId,String beginTime,String endTime) {
        List<MerchantInfoDO> merchantInfoDOList = this.baseMapper.findMerchantSignInfo(merchantId,beginTime,endTime);
        List<MerchantInfoBO> usedList = new ArrayList<>();
        merchantInfoDOList.forEach(m->{
            usedList.add(MerchantInfoBO.builder()
                    .merchantName(m.getMerchantName())
                    .deviceCount(m.getDeviceCount())
                    .build());
        });

        //获取每个商户的购买信息
        List<UserBuyDeviceDO> userBuyDeviceDOS = buyDeviceInfoMapper.findBuyDeviceInfo();
        List<MerchantInfoBO> buyList = new ArrayList<>();
        userBuyDeviceDOS.forEach(u->{
            buyList.add(MerchantInfoBO.builder()
                    .merchantName(u.getUserName())
                    .deviceCount(u.getDeviceCount())
                    .build());
        });

        List<MerchantInfoBO> remainingList = new ArrayList<>();

        buyList.forEach(b->{
            AtomicReference<Integer> deviceCount = new AtomicReference<>(b.getDeviceCount());

            usedList.forEach(u->{
                if (b.getMerchantName().equals(u.getMerchantName())){
                    //计算剩余数量
                    deviceCount.set(b.getDeviceCount() - u.getDeviceCount());
                }
            });

            remainingList.add(MerchantInfoBO.builder()
                    .merchantName(b.getMerchantName())
                    .deviceCount(deviceCount.get())
                    .build());
        });

        return MerchantBO.builder()
                .usedBO(usedList)
                .buyBO(buyList)
                .remainingBO(remainingList)
                .build();
    }

    private boolean isAdmin(){
        return ShiroKit.isAdmin();
    }
}
